package com.xyh.transaction.utils;


//import com.cloudinary.Cloudinary;
//import com.cloudinary.Transformation;
//import com.cloudinary.utils.ObjectUtils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.synonym.Synonym;
import com.hankcs.hanlp.corpus.synonym.SynonymHelper;
import com.hankcs.hanlp.dictionary.CoreSynonymDictionary;
import com.hankcs.hanlp.dictionary.common.CommonSynonymDictionary;
import com.xyh.transaction.entity.dto.MessagesDTO;
import com.xyh.transaction.entity.dto.RequestMessageDto;
import com.xyh.transaction.entity.dto.ResponseMessageDto;
import com.xyh.transaction.exception.ImageOperationException;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
public class ImageUtils {

    private static final String ACCESS_KEY = "ZkI49T0lg1gLLlssq0CuHY9gc4YJiyDdLQlGnbqd2f0";
    private static final String API_URL = "https://api.unsplash.com/photos/random?count=10";
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
    // 批量下载url
//    private static final String API_URL = "https://api.unsplash.com/photos?page=1&per_page=11";

    @Value("${image.enableLocal}")
    private boolean enableLocal;

    @Value("${image.cosEndpoint}")
    private String cosEndpoint;

    // 临时实例变量，用于接收配置注入
    @Value("${image.localUrl}")
    private String localUrl;

    // 增加方法用于根据相对路径构建完整URL
    public String buildImageUrl(String relativePath) {
        // 拼接基础URL和相对路径，构建完整访问URL
        if (enableLocal) {
            return localUrl + relativePath;
        }
        return cosEndpoint + relativePath;
    }

    public static MultipartFile bufferedImageToMultipartFile(BufferedImage bufferedImage,
                                                             String formatName,
                                                             String fileName,
                                                             String originFileName) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (!ImageIO.write(bufferedImage, formatName, os)) {
            throw new IOException("无法将图像写入输出流");
        }
        byte[] imageBytes = os.toByteArray();
        return new ConvertToMultipartFile(imageBytes, fileName, originFileName, formatName, imageBytes.length);
    }

//    private static void testCloudinaryTransformation(File imageFile) throws IOException {
//        try (InputStream inputStream = new FileInputStream(imageFile)) {
//            Cloudinary cloudinary = new Cloudinary(ObjectUtils.asMap(
//                    "cloud_name", "dj7vhbsrt",
//                    "api_key", "384768886958821",
//                    "api_secret", "5fQkhs9IEpz_KB7us0N1Xq8J-Mc"));
//
//            BufferedImage originalImage = ImageIO.read(inputStream);
//            int squareSize = Math.min(originalImage.getWidth(), originalImage.getHeight());
//
//            // Transform
//            String url = cloudinary.url().transformation(
//                            new Transformation()
//                                    .width(squareSize)
//                                    .height(squareSize)
//                                    .crop("fill"))
//                    .generate("olympic_flag");
//
//            System.out.println("Cloudinary URL: " + url);
//        }
//    }

    /**
     * 从 URL 中提取文件名
     *
     * @param url 需要提取文件名的 URL
     * @return 文件名（如果 URL 格式正确），否则返回空字符串
     */
    public static String getFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        // 将反斜杠替换为斜杠
        url = url.replace("\\", "/");

        // 使用最后一个 "/" 后的字符串作为文件名
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public static void testCropToSquare(File imageFile) throws IOException {
        try (InputStream inputStream = new FileInputStream(imageFile)) {
            BufferedImage originalImage = ImageIO.read(inputStream);
            int squareSize = Math.min(originalImage.getWidth(), originalImage.getHeight());

            int x = (originalImage.getWidth() - squareSize) / 2;
            int y = (originalImage.getHeight() - squareSize) / 2;
            BufferedImage scaledImage = originalImage.getSubimage(x, y, squareSize, squareSize);

            // Save the scaled image for visual inspection
            File scaledFile = new File("C:\\xiaoyh\\images\\scale\\scaledImage.jpg");
            ImageIO.write(scaledImage, "jpg", scaledFile);

            System.out.println("Scaled Image saved to: " + scaledFile.getAbsolutePath());
        }
    }

    public static InputStream cropToSquare(InputStream file, String formatName) throws Exception {
        try {
            BufferedImage originalImage = ImageIO.read(file);
            int minWidth = 500; // 设置默认宽度
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            if (width < minWidth) {
                int paddingWidth = minWidth - width;
                BufferedImage paddedImage = new BufferedImage(minWidth, height, BufferedImage.TYPE_INT_RGB); // 使用兼容类型
                Graphics2D g2d = paddedImage.createGraphics();
                Color leftEdgeColor = new Color(originalImage.getRGB(0, 0));
                g2d.setColor(leftEdgeColor);
                g2d.fillRect(0, 0, paddingWidth / 2, height);
                g2d.fillRect(minWidth - paddingWidth / 2, 0, paddingWidth / 2, height);
                g2d.drawImage(originalImage, paddingWidth / 2, 0, null);
                g2d.dispose();
                originalImage = paddedImage;
            }

            int squareSize = Math.min(originalImage.getWidth(), originalImage.getHeight());
            int x = (originalImage.getWidth() - squareSize) / 2;
            int y = (originalImage.getHeight() - squareSize) / 2;
            BufferedImage croppedImage = originalImage.getSubimage(x, y, squareSize, squareSize);

            // 转换为兼容的 BufferedImage 类型
            BufferedImage compatibleImage = new BufferedImage(squareSize, squareSize, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = compatibleImage.createGraphics();
            g2d.drawImage(croppedImage, 0, 0, null);
            g2d.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (!ImageIO.write(compatibleImage, formatName, baos)) {
                throw new IOException("无法将裁剪后的图像写入输出流");
            }
            return new ByteArrayInputStream(baos.toByteArray());
        } catch (Exception e) {
            throw new Exception("裁剪图像为正方形时发生错误", e);
        } finally {
            file.close();
        }
    }

    public static InputStream cropToCustomSize(InputStream file, int targetWidth, int targetHeight, String formatName) throws IOException {
        try {
            BufferedImage originalImage = ImageIO.read(file);
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            // 计算缩放比例
            double scaleX = (double) targetWidth / width;
            double scaleY = (double) targetHeight / height;
            double scale = Math.max(scaleX, scaleY);

            // 计算裁剪后的宽高
            int newWidth = (int) (width * scale);
            int newHeight = (int) (height * scale);

            // 创建缩放后的图像
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
            Graphics2D g2d = scaledImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
            g2d.dispose();

            // 裁剪中心部分
            int x = (newWidth - targetWidth) / 2;
            int y = (newHeight - targetHeight) / 2;
            BufferedImage croppedImage = scaledImage.getSubimage(x, y, targetWidth, targetHeight);

            // 将裁剪后的图像写入输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (!ImageIO.write(croppedImage, formatName, baos)) {
                throw new IOException("无法将裁剪后的图像写入输出流");
            }
            return new ByteArrayInputStream(baos.toByteArray());
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }

    public static MultipartFile cropToSquare(MultipartFile imageFile, String filename) throws IOException {
        try (InputStream inputStream = imageFile.getInputStream()) {

            String originalFilename = imageFile.getOriginalFilename();

            if (originalFilename == null || !originalFilename.contains(".")) {
                throw new IllegalArgumentException("无效的文件格式");
            }

            String formatName = "png";
            // 上传的图片格式
//            String formatName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);

            BufferedImage originalImage = ImageIO.read(inputStream);

            // 确定正方形的边长
            int squareSize = Math.min(originalImage.getWidth(), originalImage.getHeight());

            // 计算裁剪区域的左上角坐标
            int x = (originalImage.getWidth() - squareSize) / 2;
            int y = (originalImage.getHeight() - squareSize) / 2;

            // 创建正方形的裁剪后的图像
            BufferedImage croppedImage = new BufferedImage(squareSize, squareSize, originalImage.getType());

            // 获取图像的图形上下文
            Graphics2D g2d = croppedImage.createGraphics();

            // 执行裁剪
            g2d.drawImage(originalImage, 0, 0, squareSize, squareSize, x, y, x + squareSize, y + squareSize, null);

            // 释放资源
            g2d.dispose();

            return bufferedImageToMultipartFile(croppedImage, formatName, filename, originalFilename);


        } catch (IOException e) {
            throw new IOException("裁剪图片发送异常!", e);
        }
    }

    // 新增的网络图片下载方法
    public static byte[] downloadImage(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        }
    }

    public static MultipartFile resizeImage(MultipartFile file, String fileName, String formatName, double ratio) throws Exception {
        try {
            // 上传的图片格式
//            String formatName = "png";

            // 读取原始图像并裁剪为正方形
            BufferedImage cropImage = ImageIO.read(cropToSquare(file.getInputStream(), formatName));

            //
            int newWith = (int) (cropImage.getWidth() * ratio);
            int newHeight = (int) (cropImage.getHeight() * ratio);

            // 使用 Thumbnails 进行缩放
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Thumbnails.of(cropImage)
                    .outputQuality(ratio)
                    .size(newWith, newHeight)
                    .outputFormat(formatName)
                    .toOutputStream(outputStream);

            // 将压缩后的图像转换为 MultipartFile
            return new ConvertToMultipartFile(outputStream.toByteArray(), fileName, file.getOriginalFilename(), formatName, outputStream.size());
        } catch (Exception e) {
            throw new IOException("调整图像大小时发生错误", e);
        }
    }

    public static MultipartFile resizeImage(MultipartFile file, String fileName, String formatName) throws Exception {
        try {

            // 读取原始图像并裁剪为正方形
            BufferedImage cropImage = ImageIO.read(cropToCustomSize(file.getInputStream(), 947, 473, formatName));

            //
            int newWith = (int) (cropImage.getWidth());
            int newHeight = (int) (cropImage.getHeight());

            // 使用 Thumbnails 进行缩放
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Thumbnails.of(cropImage)
                    .outputQuality(1)
                    .size(newWith, newHeight)
                    .outputFormat(formatName)
                    .toOutputStream(outputStream);

            // 将压缩后的图像转换为 MultipartFile
            return new ConvertToMultipartFile(outputStream.toByteArray(), fileName, file.getOriginalFilename(), formatName, outputStream.size());
        } catch (Exception e) {
            throw new IOException("调整图像大小时发生错误", e);
        }
    }

    public static MultipartFile resizeImage(MultipartFile file, String fileName, int newWidth, int newHeight) throws Exception {
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.contains(".")) {
                throw new IllegalArgumentException("无效的文件格式");
            }
            // 上传的图片格式
//            String formatName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            String formatName = "png";
            BufferedImage cropImage = ImageIO.read(cropToSquare(file.getInputStream(), formatName));
            double aspectRatio = (double) cropImage.getWidth() / cropImage.getHeight();
            if (newWidth <= 0) {
                newWidth = (int) (newHeight * aspectRatio);
            } else if (newHeight <= 0) {
                newHeight = (int) (newWidth / aspectRatio);
            }
            Image scaledImage = cropImage.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING);
            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = resizedImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2d.drawImage(scaledImage, 0, 0, newWidth, newHeight, null);
            g2d.dispose();
            return bufferedImageToMultipartFile(resizedImage, formatName, fileName, originalFilename);
        } catch (Exception e) {
            throw new ImageOperationException("压缩图片发生错误", e);
        }
    }

    /*
    int x: 裁剪区域的左上角横坐标。这是一个整数值，表示从原始图像的哪个横坐标开始进行裁剪。
    int y: 裁剪区域的左上角纵坐标。这是一个整数值，表示从原始图像的哪个纵坐标开始进行裁剪。
    int cropWidth: 裁剪区域的宽度。这是一个整数值，表示裁剪的区域在横向上的宽度。
    int cropHeight: 裁剪区域的高度。这是一个整数值，表示裁剪的区域在纵向上的高度。
     */
//    public static InputStream cropImage(InputStream file, int x, int y, int cropWidth, int cropHeight) {
//        try {
//            // 读取原始图片
//            BufferedImage originalImage = ImageIO.read(file);
//
//            // 确保裁剪区域在图像范围内
//            int imageWidth = originalImage.getWidth();
//            int imageHeight = originalImage.getHeight();
//
//            x = Math.max(0, Math.min(x, imageWidth - 1));
//            y = Math.max(0, Math.min(y, imageHeight - 1));
//
//            cropWidth = Math.min(cropWidth, imageWidth - x);
//            cropHeight = Math.min(cropHeight, imageHeight - y);
//
//            // 创建裁剪后的图片
//            BufferedImage croppedImage = originalImage.getSubimage(x, y, cropWidth, cropHeight);
//
//            return bufferedImageToMultipartFile(croppedImage);
//
//            // 保存新的图片
//            // ImageIO.write(croppedImage, "png", new File(outputPath));
//            // System.out.println("图片已裁剪并保存成功。");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    public static void downloadImageOnline(ArrayList<String> imageUrlList) {
        for (String imageUrl : imageUrlList) {
            try {
                // 也可以是.webp格式
                //        String destinationPath = "C:\\\\xiaoyh\\\\images\\\\"+UUID.randomUUID()+".webp";
//                String destinationPath = "C:\\\\xiaoyh\\\\images\\\\" + UUID.randomUUID() + new Random().nextInt() + ".jpg";
                String destinationPath = "C:\\\\xiaoyh\\\\images\\\\" + UUID.randomUUID() + new Random().nextInt() + ".png";
//                String destinationPath = "E:\\images\\" + UUID.randomUUID() + ".jpg";

                URL url = new URL(imageUrl);
                Path destination = Paths.get(destinationPath);

                // 发起HTTP请求并将图片保存到本地
                Files.copy(url.openStream(), destination, StandardCopyOption.REPLACE_EXISTING);

                System.out.println("图片下载成功，保存在：" + destinationPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static ArrayList<String> imgUrlList() throws IOException {

        // 下载一张图片 示例用法
        Random random = new Random();
//        String imgUrl = "https://picsum.photos/400/500.webp?random="+random.nextInt();
        // 也可以 jpg格式
//        String imgUrl = "https://picsum.photos/400/500.jpg?random="+random.nextInt();

        String imgUrl = "https://picsum.photos/v2/list?width=996&height=132&page=2&limit=100";

//        String imgUrl = "https://picsum.photos/1920/488?random="+random.nextInt();
        URL url = new URL(imgUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 读取 API 响应并解析图片 URL
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 将 JSON 字符串转换为 JsonNode 对象
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(response.toString());

        ArrayList<String> list = new ArrayList<>();

        for (JsonNode node : jsonNode) {
            list.add(String.valueOf(node.get("download_url")).replaceAll("\"", ""));
        }

        return list;
    }

    private static void downloadAndSaveRandomImage(String apiKey, String destinationPath) {
        String apiUrl = "https://api.pexels.com/v1/curated?per_page=1"; // 获取一张精选照片

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);  // 修改这一行

            int responseCode = connection.getResponseCode();
            System.out.println(connection);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取 API 响应并解析图片 URL
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析图片 URL
                String imageUrl = parseImageUrl(response.toString());

                // 下载并保存图片
                downloadAndSaveImage(imageUrl, destinationPath);
            } else {
                System.out.println("API请求失败，响应代码：" + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String parseImageUrl(String jsonResponse) {
        // 解析 JSON 响应获取图片 URL，这里简化处理，请根据实际 API 响应结构来解析
        // 实际应用中你可能需要使用 JSON 解析库，比如 Jackson 或 Gson
        return jsonResponse.split("\"url\":\"")[1].split("\"")[0];
    }

    private static void downloadAndSaveImage(String imageUrl, String destinationPath) {
        try (InputStream in = new URL(imageUrl).openStream();
             OutputStream out = Files.newOutputStream(Paths.get(destinationPath))) {

            // 下载并保存图片
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            System.out.println("图片下载成功，保存在：" + destinationPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadRandomUnsplashImage(String destinationPath) {
        try {
            // 构建 API 请求
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Client-ID " + ACCESS_KEY);

            // 处理 API 响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析 JSON 响应
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.toString());

//            System.out.println(response);

            // 提取图片 URL
            for (JsonNode node : jsonNode) {
                String imageUrl = node.get("urls").get("regular").asText();
                String downloadUrl = node.get("links").get("download").asText();
                System.out.println("downloadUrl：" + downloadUrl);
                // 下载图片
                downloadImage(downloadUrl, destinationPath + UUID.randomUUID() + ".png");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadImage(String imageUrl, String destinationPath) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 下载并保存图片
            Files.copy(connection.getInputStream(), Paths.get(destinationPath), StandardCopyOption.REPLACE_EXISTING);

            System.out.println("图片下载成功，保存在：" + destinationPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final String IMAGE_TYPE = "jpg"; // 指定图片类型
    private static final String DOWNLOAD_DIR = "C:\\xiaoyh\\images\\"; // 下载目录
    private static final int MIN_WIDTH = 400; // 最小宽度
    private static final int MIN_HEIGHT = 400; // 最小高度
    private static final String BASE_URL = "https://cn.bing.com/images/search?q=%s&form=ANNTH1&first=%d&ensearch=1";
    private static final int DOWNLOAD_LIMIT = 10;
    private static final String SEARCH_VALUE = "phone";

    private static final int THREAD_COUNT = 5; // 线程数

    public static ArrayList<String> downloadLargeImages(String searchValue, String downloadDir, Integer limit) {
        int downloadLimit = (limit == null) ? DOWNLOAD_LIMIT : limit;
        ArrayList<String> result = new ArrayList<>();
        Set<String> downloadedImages = new HashSet<>(); // 用于避免重复下载
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        int pageNumber = 1; // 页码从1开始

        while (result.size() < downloadLimit) {
            try {
                String searchUrl = String.format(BASE_URL, searchValue, pageNumber * 36);
                Document document = Jsoup.connect(searchUrl).get();
                Elements linkElements = document.select("a[class*='iusc']");

                if (linkElements.isEmpty()) {
                    System.out.println("没有找到更多图片，停止搜索。");
                    break; // 如果没有更多链接，则退出循环
                }

                for (Element linkElement : linkElements) {
                    if (result.size() >= downloadLimit) {
                        break; // 如果已达到下载限制，停止循环
                    }

                    String detailPageUrl = linkElement.absUrl("href");
                    if (detailPageUrl.isEmpty()) {
                        continue;
                    }

                    // 访问详情页
                    Document detailPage = Jsoup.connect(detailPageUrl).get();
                    Element largeImageElement = detailPage.select("img").first();

                    if (largeImageElement != null) {
                        String largeImageUrl = largeImageElement.absUrl("src");

                        if (!largeImageUrl.startsWith("data:image/") && isValidImageUrl(largeImageUrl) && downloadedImages.add(largeImageUrl)) {
                            executor.submit(() -> {
                                String imageUrl = downloadImageOnline(largeImageUrl, downloadDir);
                                if (StringUtils.isNotBlank(imageUrl)) {
                                    synchronized (result) { // 确保线程安全
                                        result.add(imageUrl);
                                    }
                                }
                            });
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("数量未满足，下一页 " + (pageNumber + 1) + "，当前页码：" + pageNumber);

            pageNumber++;

            if (pageNumber > 5) {
                CommonSynonymDictionary.SynonymItem item = CoreSynonymDictionary.get(searchValue);
                if (item != null) {
                    searchValue = item.randomSynonym().getRealWord();
                    System.out.println("替换后的关键词：" + searchValue);
                } else {
                    searchValue = generateFallbackKeyword(searchValue);
                    System.out.println("没有同义词，手动处理。");
                }
                pageNumber = 1;
                System.out.println("数量未满足。换一个关键词：" + searchValue + " 并重置页码。");
            }
        }

        executor.shutdown(); // 关闭线程池
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { // 等待任务完成，设定超时时间
                executor.shutdownNow(); // 若超时则强制关闭
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt(); // 重新设置中断状态
        }

        System.out.println("最终下载到的图片数量: " + result.size());
        return result;
    }


    private static final String[] FALLBACK_KEYWORDS = {"价格", "高清图", "壁纸", "大图", "下载"};
    private static final Set<String> generatedKeywords = new HashSet<>();
    private static final Random random = new Random();

    public static String generateFallbackKeyword(String baseKeyword) {
        String fallbackWord;
        String generatedKeyword;
        long timestamp = System.currentTimeMillis(); // 使用当前时间戳代替页码

        do {
            // 随机选择一个备用词
            fallbackWord = FALLBACK_KEYWORDS[random.nextInt(FALLBACK_KEYWORDS.length)];
            int randomNumber = random.nextInt(1000) + (int)(timestamp % 1000); // 保持随机性

            // 随机决定插入位置：0为前，1为中间，2为尾
            int position = random.nextInt(3);
            switch (position) {
                case 0:
                    generatedKeyword = fallbackWord + " " + baseKeyword + " " + randomNumber;
                    break;
                case 1:
                    int insertPosition = random.nextInt(baseKeyword.length());
                    generatedKeyword = new StringBuilder(baseKeyword)
                            .insert(insertPosition, " " + fallbackWord + " ")
                            .append(" ").append(randomNumber)
                            .toString();
                    break;
                default:
                    generatedKeyword = baseKeyword + " " + fallbackWord + " " + randomNumber;
            }
        } while (generatedKeywords.contains(generatedKeyword));

        generatedKeywords.add(generatedKeyword);
        return generatedKeyword;
    }

    public static boolean isValidImageUrl(String imgUrl) {
        BufferedInputStream in = null;
        try {
            // Step 1: 发送 HEAD 请求以获取头部信息
            HttpURLConnection connection = (HttpURLConnection) new URL(imgUrl).openConnection();
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(3000);
            connection.connect();

            // Step 2: 检查 Content-Type 和 Content-Length
            String contentType = connection.getContentType();
            int contentLength = connection.getContentLength();
            if (contentType == null || !contentType.startsWith("image/") || contentLength <= 0) {
                return false;
            }

            // Step 3: 获取图像内容
            connection = (HttpURLConnection) new URL(imgUrl).openConnection(); // 重新打开连接获取图像数据
            connection.setRequestMethod("GET");
            in = new BufferedInputStream(connection.getInputStream());
            BufferedImage img = ImageIO.read(in);

            // Step 4: 验证是否成功解析为 BufferedImage 对象及检查宽高
            return img != null && img.getWidth() >= MIN_WIDTH && img.getHeight() >= MIN_HEIGHT;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 确保 BufferedInputStream 被关闭
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }


    private static boolean isUrlAccessible(String imgUrl) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(imgUrl).openConnection();
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(3000); // 设置连接超时
            connection.setReadTimeout(3000); // 设置读取超时
            connection.connect();

            // 检查响应码
            return (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static boolean isHighQualityImage(String imgUrl) {
        BufferedInputStream in = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(imgUrl).openConnection();
            connection.setRequestMethod("HEAD");
            connection.connect();

            // 获取图片的内容长度和类型
            String contentType = connection.getContentType();
            int contentLength = connection.getContentLength();

            // 确保是图片格式且内容长度合理
            if (contentType != null && contentType.startsWith("image/") && contentLength > 0) {
                connection = (HttpURLConnection) new URL(imgUrl).openConnection(); // 重新打开连接获取图像数据
                connection.setRequestMethod("GET");
                in = new BufferedInputStream(connection.getInputStream());
                BufferedImage img = ImageIO.read(in);

                // 检查 img 是否为 null，且检查图片尺寸
                if (img != null && img.getWidth() >= MIN_WIDTH && img.getHeight() >= MIN_HEIGHT) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 确保 BufferedInputStream 被关闭
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }


    private static String downloadImageOnline(String imgUrl, String destinationPath) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(imgUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 检查响应代码
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 检查并创建目录
                File dir = new File(destinationPath);
                if (!dir.exists() && dir.mkdirs()) {
                    System.out.println("创建目录: " + destinationPath);
                }

                // 生成唯一文件名
                UUID uuid = UUID.randomUUID();
                String fileName = destinationPath + File.separator + uuid + "." + IMAGE_TYPE;

                // 读取输入流并裁剪/压缩图片
                try (InputStream inputStream = connection.getInputStream()) {
                    MultipartFile multipartFile = resizeImage(new ConvertToMultipartFile(inputStream, uuid.toString(), "网络下载图片", IMAGE_TYPE), uuid.toString(), IMAGE_TYPE, 1);

                    // 保存文件，使用分块写入优化速度
                    try (OutputStream out = Files.newOutputStream(Paths.get(fileName))) {
                        // 定义 8KB 的缓冲区大小
                        byte[] buffer = new byte[8192];
                        InputStream in = multipartFile.getInputStream();
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                        System.out.println("图片保存地址：" + fileName);
                        return fileName;
                    }
                } catch (Exception e) {
                    log.error("图片下载失败: ", e);
                    throw new RuntimeException(e);
                }
            } else {
                System.out.println("无法下载: " + imgUrl);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return "";
    }

    private static String getFileName(String imgUrl) {
        return imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
    }

    private static String aiResponse(String inputText) {
        try {
            // 测试GET请求
            String authorizationHeader = "Bearer irvhOUpiUlGSUbKurNzX:fcOEbYOfEurFrEkXsxsR";
            String response = "";

            // 测试POST请求
            RequestMessageDto requestMessageDto = new RequestMessageDto();
            requestMessageDto.setModel("general");
            requestMessageDto.setStream(false);
            MessagesDTO messagesDTO = new MessagesDTO();
            messagesDTO.setRole("user");
            messagesDTO.setContent("这个词：" + inputText + " 的同义词是？");
            ArrayList<MessagesDTO> messagesDTOArrayList = new ArrayList<MessagesDTO>();
            messagesDTOArrayList.add(messagesDTO);
            requestMessageDto.setMessages(messagesDTOArrayList);
            response = HttpUtil.sendPost("https://spark-api-open.xf-yun.com/v1/chat/completions", JSON.toJSONString(requestMessageDto), authorizationHeader);
//            System.out.println("POST Response: " + response);
            System.out.println(JSON.parseObject(response, ResponseMessageDto.class).getChoices().get(0).getMessage().getContent());
            return JSON.parseObject(response, ResponseMessageDto.class).getChoices().get(0).getMessage().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static List<String> expandKeywords(String keyword) {
        List<String> expandedKeywords = new ArrayList<>();

        // 添加原始关键词
        expandedKeywords.add(keyword);

        // 调用API获取同义词
        String apiUrl = "https://api.datamuse.com/sug?s=" + keyword; // 示例URL，可能需要根据API文档调整
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON响应
            JSONArray suggestions = new JSONArray(response.toString());
            for (int i = 0; i < suggestions.length(); i++) {
                JSONObject suggestion = suggestions.getJSONObject(i);
                expandedKeywords.add(suggestion.getString("word")); // 根据API返回的字段解析
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return expandedKeywords;
    }

    public static void main(String[] args) throws IOException {
        // 示例用法

        System.out.println(generateFallbackKeyword("手机"));


//        downloadLargeImages("平板电脑",DOWNLOAD_DIR + "平板电脑\\",13);
//        downloadLargeImages("教材",DOWNLOAD_DIR + "教材\\",1);
//        downloadLargeImages("生活",DOWNLOAD_DIR + "生活\\",1);
//        downloadLargeImages("健身",DOWNLOAD_DIR + "健身\\",1);
//        downloadLargeImages("美妆",DOWNLOAD_DIR + "美妆\\",1);
//        downloadLargeImages("文娱",DOWNLOAD_DIR + "文娱\\",1);
//        downloadLargeImages("艺术",DOWNLOAD_DIR + "艺术\\",1);

//        String destinationPath = "E:\\images\\";
//        downloadRandomUnsplashImage(destinationPath);
//
//        String patch = "C:\\xiaoyh\\images\\1c7ad5cb-1141-439d-b016-290e38bbc31d.jpg";
//
//        File imageFile = new File(patch);
//
////        testCloudinaryTransformation(imageFile);
//        testCropToSquare(imageFile);


//        ArrayList<String> list = imgUrlList();
//
//        downloadImage(list);

//        String destinationPath = "C:\\\\xiaoyh\\\\images\\\\" + UUID.randomUUID() + UUID.randomUUID() + ".png";

//        Random random = new Random(10000);
//        for (int i = 0; i < 10; i++) {
////            String destinationPath = "C:\\\\xiaoyh\\\\images\\\\" + UUID.randomUUID() + UUID.randomUUID() + ".png";
////            downloadAndSaveImage("https://picsum.photos/1920/488?random=" + random.nextInt(), destinationPath);
//            String destinationPath = "E:\\images\\" + UUID.randomUUID() + UUID.randomUUID() + ".jpg";
//            downloadAndSaveImage("https://picsum.photos/943/487?random=" + random.nextInt(), destinationPath);
//        }

//        downloadRandomUnsplashImage("C:\\\\xiaoyh\\\\images\\\\1\\\\");
//
//        downloadAndSaveRandomImage()
//        // 用不了
////        String apiKey = "cjKqYHm2E5jwPhzzgGyjMeJVuj3y7LvxbQcuLYJDC3DaiWwSEtVufhtL";
////        downloadAndSaveRandomImage(apiKey,destinationPath);
//
////        URL url = new URL("https://api.pexels.com/v1/search?query=nature&per_page=1");
////        System.out.println(url);
//
//        // 示例用法
////        String inputPath = "C:\\\\Users\\\\xiaoyh\\\\Pictures\\\\Camera Roll\\\\QQ截图20231130112319.png";
////        String outputPath = "C:\\\\xiaoyh\\\\images\\\\"+UUID.randomUUID() + ".png";
////        int newWidth = 300; // 或者设为负数，表示根据高度等比例缩放
////        int newHeight = -200; // 或者设为负数，表示根据宽度等比例缩放
////
////        resizeImage(inputPath, outputPath, newWidth, newHeight);
    }
}
